package com.hn.shirojwt.component;

import com.hn.shirojwt.util.JwtTokenUtil;
import org.apache.shiro.web.filter.authz.AuthorizationFilter;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * 实现roles["admin,test"]或关系
 * @ClassName:CustomRolesAuthorizationFilter
 * @author:Wanghao
 * @date: 2017年9月27日 下午5:27:58
 */

public class MyRolesFliter extends AuthorizationFilter{

    JwtTokenUtil jwtTokenUtil = new JwtTokenUtil();

    private final String TOKENHEADER = "Authorization";


    @Override
    protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue)
            throws Exception {

        String token;
        //过滤跨域的OPTIONS请求
        if (((HttpServletRequest) request).getMethod().toUpperCase().equals("OPTIONS"))
            return true;

        //校验token是否正确
        try {
            HttpServletRequest req = (HttpServletRequest) request;
            token = req.getHeader(TOKENHEADER);
            boolean flag = jwtTokenUtil.validateToken(token);
            if(flag==false)
                return false;
        }catch(Exception e) {
            return false;
        }

        String[] rolesArray = (String[]) mappedValue;
        //没有角色限制，有权限访问
        if (rolesArray == null || rolesArray.length == 0) {
            return true;
        }

        //获取用户角色
        String role = jwtTokenUtil.getRoleFromToken(token);
        if(role==null)
            return false;


        //包含角色则有权访问
        for (String s : rolesArray) {
            if(role.equals(s)){
                return true;
            }
        }
        return false;
    }
    
    @Override
    protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws IOException {
    	HttpServletResponse res = (HttpServletResponse)response;
        res.setHeader("Access-Control-Allow-Origin", "*");
        res.setStatus(HttpServletResponse.SC_OK);
        res.setCharacterEncoding("UTF-8");
        PrintWriter writer = res.getWriter();
        //返回未授权
        writer.write("权限不足");
        writer.close();
        return false;
    }
}
